package com.monizhuang;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Map;

@RestController
public class MoniController {

    private static final Logger logger = LoggerFactory.getLogger(MoniController.class);
    private static final String MONI_JSON_PATH = "/moni.json";

    @GetMapping("moni/**")
    public ResponseEntity<String> moniGet(HttpServletRequest request) {
        return processRequest(request);
    }

    @PostMapping("moni/**")
    public ResponseEntity<String> moniPost(@RequestBody(required = false) String requestBody, HttpServletRequest request) {
        return processRequest(requestBody, request);
    }

    private ResponseEntity<String> processRequest(String requestBody, HttpServletRequest request) {
        String path = request.getRequestURI().replaceFirst("^/moni", "");
        logger.info("模拟桩打印路径: {}", path);
        printRequestParameters(request, requestBody);

        try {
            File resource = new File(MONI_JSON_PATH);
            if (resource.exists()) {
                String mapJson = new String(Files.readAllBytes(resource.toPath()), StandardCharsets.UTF_8);
                JSONObject jsonObject = JSON.parseObject(mapJson);
                String data = jsonObject.getString(path);

                if (data != null) {
                    return ResponseEntity.ok(data);
                } else {
                    return ResponseEntity.notFound().build();
                }
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
        } catch (IOException e) {
            logger.error("Error reading file", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    private void printRequestParameters(HttpServletRequest request, String requestBody) {
        StringBuilder urlParamsInfo = new StringBuilder();

        // Print URL parameters
        Map<String, String[]> urlParams = request.getParameterMap();
        urlParams.forEach((key, values) -> {
            urlParamsInfo.append(key).append(" = ").append(String.join(", ", values)).append("; ");
        });
        logger.info("模拟桩打印地址参数: {}" + urlParamsInfo.toString().trim().replaceAll(";$", ""));

        StringBuilder bodyParamsInfo = new StringBuilder();
        String contentType = request.getContentType();
        if (contentType.startsWith("application/x-www-form-urlencoded")) {
            Map<String, String[]> bodyParams = request.getParameterMap();
            bodyParams.forEach((key, values) -> {
                bodyParamsInfo.append(key).append(" = ").append(String.join(", ", values)).append("; ");
            });
            logger.info("模拟桩打印表单参数: {}", bodyParamsInfo.toString().trim().replaceAll(";$", ""));
        } else if (requestBody != null && !requestBody.isEmpty()) {
            // Print body parameters for other types of content (like JSON)
            JSONObject bodyJson = JSON.parseObject(requestBody);
            bodyJson.forEach((k, v) -> bodyParamsInfo.append(k).append(" = ").append(v).append("; "));
            logger.info("模拟桩打印body参数: {}", bodyParamsInfo.toString().trim().replaceAll(";$", ""));
        }
    }

    // For GET requests where there's no requestBody, we can provide an overload without it
    private ResponseEntity<String> processRequest(HttpServletRequest request) {
        return processRequest(null, request);
    }
}